package gen

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"gitee.com/krio/ginc/util"
	"github.com/gookit/color"
)

// HandleTagGen 使用inject_tag处理pb的tag
// 项目地址：github.com/favadi/protoc-go-inject-tag
func (g *Generator) HandleTagGen() error {
	color.Bluep("[ 处理： tag标签 ]", "\n")
	// 获取所有pb文件名称
	pbs, err := util.GetPbFiles(g.tempPbPath)
	if err != nil {
		return fmt.Errorf("GetPbFiles Failed: %+v", err)
	}
	if len(pbs) <= 0 {
		return nil
	}
	var counter int
	for _, v := range pbs {
		cmd := exec.Command("protoc-go-inject-tag", fmt.Sprintf("-input=%s", v))
		cmd.Stderr = os.Stderr
		_, err = cmd.Output()
		if err != nil {
			return err
		}
		// 去除结构体的忽略标签 omitempty
		err = delTag(v)
		if err != nil {
			panic(err)
		}
		counter++
	}
	color.Cyanp(fmt.Sprintf("|* 处理pb数量:%d \n", counter))
	return nil
}

// 调整pb的tag（主要批量清除json标签里的omitempty）
func delTag(fileName string) error {
	b, err := os.ReadFile(fileName)
	if err != nil {
		return nil
	}
	pb := string(b)
	pb = strings.ReplaceAll(pb, ",omitempty", "")
	return os.WriteFile(fileName, []byte(pb), 0644)
}
